//
// Created by 86186 on 2021/9/9.
//
#include <jni.h>
#include <string>
#include "header/wauxlib.h"
#include "header/wavelib.h"
#include "log.h"

using namespace std;

#define BUFFER_SIZE 10000

double *data_buffer = (double *)malloc(BUFFER_SIZE*sizeof(double));
int data_buffer_position;

/*
*   Wavelet Object, Parameters and Functions 小波对象、参数和函数
*   https://github.com/rafat/wavelib/wiki/wave-object
*   Discrete Wavelet Transform Object, Parameters and Functions 离散小波变换对象、参数和函数
*   可用的小波类型：
*   Haar : haar
*   Daubechies : db1,db2,.., ,db15
*   Biorthogonal : bior1.1 ,bior1.3 ,bior1.5 ,bior2.2 ,bior2.4 ,bior2.6 ,bior2.8 ,bior3.1 ,bior3.3 ,bior3.5 ,bior3.7 ,bior3.9 ,bior4.4 ,bior5.5 ,bior6.8
*   Coiflets : coif1,coif2,coif3,coif4,coif5
*   Symmlets: sym2,........, sym10
*   https://github.com/rafat/wavelib/wiki/wt-object
*/
const char* name = "db8";
wave_object obj = wave_init(name);// Initialize the wavelet

int J = 5; //小波包的层数
// wave - Wavelet object created using wave_object
// method - Takes char values - "dwt", "swt" and "modwt"
wt_object wt = wt_init(obj, "dwt", data_buffer_position, J);// Initialize the wavelet transform object


extern "C"
JNIEXPORT void JNICALL
Java_com_tju_statics_StaticService_00024Companion_clearDataBuffer(JNIEnv *env, jobject thiz) {
    data_buffer_position = 0;
    return;
}

double convertByte(char ch) {
    return (double)ch;
}

extern "C"
JNIEXPORT void JNICALL
Java_com_tju_statics_StaticService_00024Companion_writeBuffer(JNIEnv *env, jobject thiz,
                                                              jbyte byte) {
    unsigned char ch = byte;
    if(data_buffer_position<BUFFER_SIZE) {
        data_buffer[data_buffer_position++] = convertByte(ch);
    }
    return;
}

extern "C"
JNIEXPORT jint JNICALL
Java_com_tju_statics_StaticService_00024Companion_bufferSize(JNIEnv *env, jobject thiz) {
    return data_buffer_position;
}

extern "C"
JNIEXPORT jboolean JNICALL
Java_com_tju_statics_StaticService_00024Companion_bufferFull(JNIEnv *env, jobject thiz) {
    return data_buffer_position >= BUFFER_SIZE;
}

extern "C"
JNIEXPORT jdoubleArray JNICALL
Java_com_tju_statics_StaticService_00024Companion_waveletFilter(JNIEnv *env, jobject thiz) {
    setDWTExtension(wt, "sym");// Options are "per" and "sym". Symmetric is the default option
    setWTConv(wt, "direct");
    dwt(wt, data_buffer);// Perform DWT
    auto filter_list = env->NewDoubleArray(wt->outlength);
    jdouble filter_buf[wt->outlength];
    for(int i=0; i<wt->outlength; i++) {
        filter_buf[i] = wt->output[i];
    }
    env->SetDoubleArrayRegion(filter_list, 0, wt->outlength, filter_buf);
    return filter_list;
}
